﻿/*****************************************************************
 *Yuga Technology
 *@author Oplink OMS
 *@copyright all rights reserved (c) zengkang007@gmail.com
 *****************************************************************/
package com.oplink.webems.modules.sys.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.oplink.webems.common.persistence.Page;
import com.oplink.webems.modules.sys.dto.TreeDTO;
import com.oplink.webems.modules.sys.entity.Menu;
import com.oplink.webems.modules.sys.entity.User;
import com.oplink.webems.modules.sys.service.MenuService;
import com.oplink.webems.modules.sys.service.ShiroDbRealm.ShiroUser;
import com.oplink.webems.modules.sys.utils.DTOParseUtil;

/**
 * SysMenu管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /queue/
 * Create pushlet : GET /queue/pushlet
 * Create page : GET /queue/create
 * Create action : POST /queue/create
 * Update page : GET /queue/update/{id}
 * Update action : POST /queue/update
 * Delete action : GET /queue/delete/{id}
 * 告警Controller
 * 
 * @author Oplink OMS
 * @version 2014-09-02
 */
@Controller
@RequestMapping(value = "sys/menu")
public class MenuController extends BaseController {

	@Autowired
	private MenuService menuService;

	@RequiresPermissions("modules/sys:menu:view")
	@RequestMapping(value = { "list", "" }, method = { RequestMethod.GET, RequestMethod.POST })
	public String list(Menu menu, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Menu> pages = menuService.find(new Page<Menu>(request, response, 100), menu);
		model.addAttribute("pages", pages);
		return "modules/sys/menuList";
	}

	@RequestMapping(value = { "listDTO" }, method = { RequestMethod.GET })
	@ResponseBody
	public List<TreeDTO> listDTO() {
		List<Menu> listMenu = menuService.findAll();
		List<TreeDTO> listOut = new ArrayList<TreeDTO>();
		for (Menu menu : listMenu) {
			listOut.add(DTOParseUtil.toDTO(menu));
		}
		return listOut;
	}

	@RequiresPermissions("modules/sys:menu:edit")
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Menu updateForm(@PathVariable("id") Long id) {
		Menu menu = menuService.getSysMenu(id);
		menu.setUser(null);
		return menu;
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(@Valid @ModelAttribute("menu") Menu menu, RedirectAttributes redirectAttributes) {
		try {
			User user = new User(getCurrentUserId());
			menu.setUser(user);
			// 更新ids
			// 取最后一个节点和当前ID对比
			String ids = menu.getParentIds();
			int index = ids.lastIndexOf(".");
			ids = ids.substring(index + 1);
			if (!menu.getId().toString().equals(ids)) {
				menu.setParentIds(menu.getParentIds() + "." + menu.getId());
			}
			menuService.saveSysMenu(menu);
			redirectAttributes.addFlashAttribute("message", "更新任务成功");
			return "1";
		} catch (Exception e) {
			return "0";
		}
	}

	@RequiresPermissions("modules/sys:menu:view")
	@RequestMapping(value = "form")
	public String form(Menu menu, Model model) {
		model.addAttribute("menu", menu);
		return "modules/sys/menuForm";
	}

	@RequiresPermissions("modules/sys:menu:edit")
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("userId", getCurrentUserId());
		model.addAttribute("action", "create");
		return "modules/sys/menu/create";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public String create(Menu menu, RedirectAttributes redirectAttributes, Model model) {
		try {
			User user = new User(getCurrentUserId());
			menu.setUser(user);
			model.addAttribute("menu", menu);
			menuService.saveSysMenu(menu);
			// 更新ids
			String parentIds = (menu.getParentIds() == null) ? "0" : menu.getParentIds();
			parentIds = (parentIds.equals("")) ? menu.getId().toString() : (parentIds + "." + menu.getId());
			menu.setParentIds(parentIds);
			menuService.saveSysMenu(menu);
			redirectAttributes.addFlashAttribute("message", "创建任务成功");
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			String ret = "0";
			if (!"".equals(id)) {
				String[] delList = id.split(",");
				for (String idItem : delList) {
					menuService.deleteSysMenu(Long.valueOf(idItem));
				}
				redirectAttributes.addFlashAttribute("message", "删除任务成功");
				ret = "1";
			} else {
				ret = "0";
			}
			return ret;
		} catch (Exception e) {
			return "0";
		}
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}
}
